import Datastore from 'lowdb'
import {aesDecrypt, aesEncrypt} from '@/utils/encrypt'
import FileSync from 'lowdb/adapters/FileSync'
import path from 'path'
import sha256 from "crypto-js/sha256";
import CryptoJS from "crypto-js";
import fs from 'fs-extra'
import {app} from 'electron'

const APP = process.type === 'renderer' ? require('@electron/remote').app : app

const basePath = APP.getPath('userData')

if (process.type !== 'renderer') {
    if (!fs.pathExistsSync(basePath)) {
        fs.mkdirpSync(basePath)
    }
}


// 初始化lowdb读写的json文件名以及存储路径
class UserDB{
    constructor() {
        this._adapter = new FileSync(path.join(basePath, '/user.json')) //存储用户配置
        this._db=Datastore(this._adapter);
        this._db.defaults({
            'password':sha256('0000').toString(),
            'iv':CryptoJS.lib.WordArray.random(128/8).toString(CryptoJS.enc.Hex)
        }).write();
    };
    get adapter(){
        return this._db;
    }
}

class DataDB{
    constructor(key,iv) {
        this._key=key;
        this._iv=iv;
        this._adapter = new FileSync((path.join(basePath,'/data.json')));
        this._db=Datastore(this._adapter);
        this._db.defaults({
            'content':[],
            'history':{}
        }).write();
    };
    get adapter(){
        return this._db;
    }
    encrypt=(param)=>{
        const key=this._key;
        const iv=this._iv;
        if(param===undefined||param===null)
            return;
        if(typeof param === 'string'){
            return aesEncrypt(param,{key,iv});
        }
        if(typeof param === 'object'){
            if(param instanceof Array){
                for (let i=0;i<param.length;i++) {
                    param[i]=this.encrypt(param[i]);
                }
                return param;
            }
            if(Object.prototype.toString.call(param) === '[object Object]'){
                let newObj={};
                Object.keys(param).forEach(item=>{
                    newObj[item]=this.encrypt(param[item]);
                })
                return newObj;
            }
        }
    }
    decrypt=(param)=>{
        const key=this._key;
        const iv=this._iv;
        if (param === undefined || param === null)
            return;
        if (typeof param === 'string') {
            return aesDecrypt(param, {key, iv});
        }
        if (typeof param === 'object') {
            if (param instanceof Array) {
                for (let i = 0; i < param.length; i++) {
                    param[i] = this.decrypt(param[i]);
                }
                return param;
            }
            if (Object.prototype.toString.call(param) === '[object Object]') {
                let newObj = {};
                Object.keys(param).forEach(item => {
                    newObj[item] = this.decrypt(param[item], {key, iv});
                })
                return newObj;
            }
        }
    }
}


export {
    UserDB,DataDB
}

